package com.ghsc.ghxc.jsb.ui.live.fragment

import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.InputType
import android.text.Spanned
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.cn.appcore.base.BaseVMFragment
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.gone
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.visible
import com.cn.appcore.utils.GsonUtil
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.FragmentLiveRedBinding
import com.ghsc.ghxc.jsb.ui.message.view.PayPwdPopViiew
import com.ghsc.ghxc.jsb.utils.OnlyOneEditText
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import java.io.UnsupportedEncodingException
import java.math.BigDecimal
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.live.fragment
 * 类名：LiveRedFragment
 * 创建时间：2024/5/23 18:08
 * 创建人 @author： xiaolin
 * 描述 ：Todo...发送红包
 */
class LiveRedFragment   : BaseVMFragment<LiveRedViewModel, FragmentLiveRedBinding>(R.layout.fragment_live_red) {

    //聊天时id
    private var mGroupId: String = ""

    //主播id
    private var anchorId: String = ""

    //直播id
    private var liveId: String = ""

    companion object {
        fun newInstance(anchorId: String, mGroupId: String, liveId: String): LiveRedFragment {
            val fragment = LiveRedFragment()
            fragment.mGroupId = mGroupId
            fragment.anchorId = anchorId
            fragment.liveId = liveId
            return fragment
        }
    }

    override fun attachVMClass(): Class<LiveRedViewModel>? {
        return LiveRedViewModel::class.java
    }

    override fun lazyLoad() {

    }

    var redType: Int = 1  //类型 1 拼手气 2 普通
    var maxCount = 0  //最多数量


    var service_charge_rate:Double=0.0


    //弹框关闭回调
    private var dismiss: (() -> Unit)? = null
    fun setOnDismissListener(listener: (() -> Unit)) {
        this.dismiss = listener
    }

    override fun onResume() {
        super.onResume()
        mViewModel.onRedIndexDataMethod("")
    }

    override fun initView(savedInstanceState: Bundle?) {


    }

    override fun initData() {
        super.initData()
        binding.etNum.inputType = InputType.TYPE_CLASS_NUMBER
        setEditTextOnlyDigits(binding.etNum)

        binding.etTime.inputType = InputType.TYPE_CLASS_NUMBER
        setEditTextOnlyDigits(binding.etTime)


        //允许输入小数
        binding.etMoneyNumberAll.setInputType(InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL)
        //限制输入的位数
        binding.etMoneyNumberAll.addTextChangedListener(
            OnlyOneEditText(binding.etMoneyNumberAll).setInputNum(
                4
            )
        )

        binding.etNum.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (!TextUtils.isEmpty(binding.etMoneyNumberAll.text.toString().trim())) {
                    val money = binding.etMoneyNumberAll.text.toString().trim().toDouble()
                    if (money > 0) {
                        val price = money + (money * service_charge_rate)
                        binding.tvAll.text = String.format("%.4f", price)
                        var numStr = binding.etNum.text.toString().trim()
                        if (!TextUtils.isEmpty(numStr)) {
                            var num = numStr.toInt()
                            if (num > 0) {
                                var number = (price / num).toBigDecimal()
                                val number2 = BigDecimal("0.0001")
                                if (number >= number2) {
                                    binding.tvBtnNext.alpha = 1f
                                    binding.tvBtnNext.isEnabled = true
                                    setState(price)
                                } else {
                                    binding.tvBtnNext.alpha = 0.5f
                                    binding.tvBtnNext.isEnabled = false
                                }
                            } else {
                                binding.tvBtnNext.alpha = 0.5f
                                binding.tvBtnNext.isEnabled = false
                            }
                        } else {
                            binding.tvBtnNext.alpha = 0.5f
                            binding.tvBtnNext.isEnabled = false
                        }

                    } else {
                        binding.tvAll.text = "0.00"
                        binding.tvBtnNext.alpha = 0.5f
                        binding.tvBtnNext.isEnabled = false
                    }
                } else {
                    binding.tvAll.text = "0.00"
                    binding.tvBtnNext.alpha = 0.5f
                    binding.tvBtnNext.isEnabled = false
                }
            }

            override fun afterTextChanged(s: Editable?) {
                if (s.toString().startsWith("0") || s.toString() == "") {
                    binding.etNum.setText("1")
                    binding.etNum.setSelection(1)
                }
            }

        })
        binding.etMoneyNumberAll.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(s: CharSequence, p1: Int, p2: Int, p3: Int) {
                if (redType == 1) {
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        val money = binding.etMoneyNumberAll.text.toString().trim().toDouble()
                        loge("输入后的监听onTextChanged" + money)
                        if (money > 0) {
                            val price = money + (money * service_charge_rate)
                            binding.tvAll.text = String.format("%.4f", price)
                            var numStr = binding.etNum.text.toString().trim()
                            if (!TextUtils.isEmpty(numStr)) {
                                var num = numStr.toInt()
                                if (num > 0) {
                                    var number = (price / num).toBigDecimal()
                                    val number2 = BigDecimal("0.0001")
                                    if (number >= number2) {
                                        loge("当前true=")
                                        binding.tvBtnNext.alpha = 1f
                                        binding.tvBtnNext.isEnabled = true
                                        setState(price)
                                    } else {
                                        loge("当前false=")
                                        binding.tvBtnNext.alpha = 0.5f
                                        binding.tvBtnNext.isEnabled = false
                                    }
                                } else {
                                    binding.tvBtnNext.alpha = 0.5f
                                    binding.tvBtnNext.isEnabled = false
                                }
                            } else {
                                binding.tvBtnNext.alpha = 0.5f
                                binding.tvBtnNext.isEnabled = false
                            }

                        } else {
                            binding.tvAll.text = "0.00"
                            binding.tvBtnNext.alpha = 0.5f
                            binding.tvBtnNext.isEnabled = false
                        }
                    } else {
                        binding.tvAll.text = "0.00"
                        binding.tvBtnNext.alpha = 0.5f
                        binding.tvBtnNext.isEnabled = false
                    }
                }
            }

            override fun afterTextChanged(p0: Editable?) {
                loge("输入后的监听afterTextChanged" + p0)

            }

        })

        binding.etTime.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
                //如果起始位置为0,且第二位跟的不是".",则无法后续输入
                if (s.toString().startsWith("0")
                    && s.toString().trim { it <= ' ' }.length > 1
                ) {
                    if (s.toString().substring(1, 2) != ".") {
                        binding.etTime.setText(s!!.subSequence(0, 1))
                        binding.etTime.setSelection(1)
                        return
                    }
                }
            }

            override fun afterTextChanged(s: Editable?) {
                if (s.toString().startsWith("0") || s.toString() == "") {
                    binding.etNum.setText("0")
                    binding.etNum.setSelection(0)
                }
            }

        })
    }


    private fun setState(price: Double) {
        val hongbao = binding.usableHongbao.text.toString().toDouble()
        if (hongbao > price) {
            binding.tvBtnNext.alpha = 1.0f
            binding.tvBtnNext.isEnabled = true
        } else {
            binding.tvBtnNext.alpha = 0.5f
            binding.tvBtnNext.isEnabled = false
        }
    }

    override fun initClickListener() {
        super.initClickListener()
        binding.run {
            tvType.setSingleClickListener {
                //类型 目前只有一种
            }
            binding.tvBtnNext.setSingleClickListener {
                var count = binding.etNum.text.toString().trim()
                if (TextUtils.isEmpty(count)) {
                    showToast("请输入红包个数")
                    return@setSingleClickListener
                }
                if (count.toInt() <= 0) {
                    showToast("请输入红包个数")
                    return@setSingleClickListener
                }
                if (count.toInt() > maxCount) {
                    showToast("红包最大数量不得超过" + maxCount + "个")
                    return@setSingleClickListener
                }
                if (redType == 1) {
                    //拼手气红包
                    var amount = binding.etMoneyNumberAll.text.toString().trim()
                    if (TextUtils.isEmpty(binding.etMoneyNumberAll.text.toString().trim())) {
                        showToast("请输入红包的总数量")
                        return@setSingleClickListener
                    }

                    var money = amount.toDouble()
                    if (money <= 0) {
                        showToast("请输入红包的总数量")
                        return@setSingleClickListener
                    }


                    var time = binding.etTime.text.toString().trim()
                    if (TextUtils.isEmpty(time))
                        time = "0"

                    if (time.toInt() > 60) {
                        showToast("红包倒计时不可大于60分钟")
                        return@setSingleClickListener
                    }


                    XPopup.Builder(requireActivity())
                        .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                        .customHostLifecycle(lifecycle)
                        .autoOpenSoftInput(true)
                        .moveUpToKeyboard(true)
                        .dismissOnTouchOutside(false)
                        .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                        .asCustom(
                            PayPwdPopViiew(requireActivity(), object :
                                PayPwdPopViiew.SublickListener {
                                override fun onAdopt(pwdStr: String) {
                                    //送礼物
                                    loge("密码=" + pwdStr)
                                    showLoading()
                                    var moeo = ""
                                    if (TextUtils.isEmpty(binding.etContent.text.toString().trim()))
                                        moeo = "恭喜发财 大吉大利"
                                    else {
                                        try {
                                            moeo = URLEncoder.encode(
                                                binding.etContent.text.toString().trim(),
                                                StandardCharsets.UTF_8.toString()
                                            )
                                        } catch (e: UnsupportedEncodingException) {
                                            e.printStackTrace()
                                        }
                                    }
                                    showToast("发送直播拼手气红包")
                                    val map: HashMap<String, Any> = HashMap()
                                    map["ptype"] = redType
                                    map["count"] = count
                                    map["amount"] = money
                                    map["memo"] = moeo
                                    map["cover"] = ""
                                    map["paypassword"] = pwdStr
                                    map["im_type"] = 3
                                    map["source_id"] = liveId
                                    map["count_down"] = time
                                    map["single_price"] = money
                                    loge(
                                        "发送红包" + GsonUtil.mapToJsonStrObjEncryption(map)
                                            .toString()
                                    )
                                    GsonUtil.mapToJsonStrObjEncryption(map)
                                        ?.let { it1 -> mViewModel.onSendPacketSubmitMethod(it1) }
                                }
                            })
                        )
                        .show()
                }
            }
        }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@LiveRedFragment) {
                dismissLoading()
                showToast(it)
            }
            againLoginMsg.observe(this@LiveRedFragment) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onRedIndexData.observe(this@LiveRedFragment) {
                binding.run {
                    usableHongbao.text = it.data.jifen.toString()
                    service_charge_rate=it.data.service_charge_rate
                    if(it.data.service_charge_rate>0){
                        serviceChargeRate.visible()
                        tvGao.gone()
                        serviceChargeRate.text = "注意:发红包需支付${(it.data.service_charge_rate*100).toInt()}%手续费"
                    }else{
                        serviceChargeRate.gone()
                        tvGao.visible()
                    }
                    packetMaxCount.text = "上限发${it.data.packet_max_count}个红包"
                    maxCount = it.data.packet_max_count
                }
            }
            onSendPacketSubmitData.observe(this@LiveRedFragment) {
                dismissLoading()
                showToast("发送成功")
                RxBus.getDefault().post(
                    RxBusBean(
                        CustSignKey.CUST_LIVE_FUDAI_SUCCESS,
                        CustSignKey.CUST_LIVE_FUDAI_SUCCESS, it.data
                    )
                )
                dismiss?.invoke()
            }
//            onSendPacketSubmitData.observe(this@LiveRedFragment){
//                dismissLoading()
//                showToast("发送成功")
//                finish()
//            }
        }
    }

    // 设置EditText只能输入数字
    fun setEditTextOnlyDigits(editText: EditText) {
        val filter = object : InputFilter {
            override fun filter(
                source: CharSequence?,
                start: Int,
                end: Int,
                dest: Spanned?,
                dstart: Int,
                dend: Int
            ): CharSequence? {
                for (i in start until end) {
                    if (!Character.isDigit(source?.get(i) ?: ' ')) {
                        return ""
                    }
                }
                return null
            }
        }

        editText.filters = arrayOf(filter)
    }
}
